package com.sh.shanhuo.utils;

import android.content.Context;
import android.net.sip.SipSession;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Window;

import com.blankj.utilcode.util.ApiUtils;
import com.blankj.utilcode.util.FileUtils;
import com.sh.shanhuo.listener.SimpleResultCallback;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;

public class OkHttpUtil {
    private static final String TAG = OkHttpUtil.class.getSimpleName();

    public static final String IP = "http://114.55.174.245:8080";
    public static final String START_PAGE = "/api/user/getAppStartPage";
    public static final String NEW_VERSION = "/api/user/getAppVersion";
    public static final String CUR_VERSION = "/api/user/getAppVersionByAppVersion";
    public static final String USER_FEEDBACK = "/api/user/addFeedback";
    public static final String LOGIN = "/api/user/login";
    public static final String APP_USED_COUNT = "/api/user/updateUuid";
    public static final String UPDATE_USER = "/api/user/updateAppUser";
    public static final String ADD_USER = "/api/user/addAppUser";
    public static final String RESET_PASSWORD = "/api/user/resetPwByEmail";


    public static final String GET_SITES = "/api/web/getSiteList";
    public static final String WEB_SITES = "/api/web/getWebSiteByIds";
    public static final String ADD_SITE = "/api/web/addSite";
    public static final String CHECK_SITE = "/api/web/checkSite";
    public static final String COUNT_SITE_VIEWS = "/api/web/statisticalWebUrl";
    public static final String UPDATE_SITES = "/api/web/updateSite";
    public static final String GET_CATE_LIST = "/api/web/getCateList";
    public static final String SEARCH_LIST = "/api/web/getSearchList";

    public static final String UPLOAD_IMAGE = "/common/upload";

    public static final String PERSONAL_CENTER_LIST = "/api/user/getPersonalCenterList";
    public static final String NOTICE_LIST = "/api/user/getNoticeList";
    public static final String PUSH_LIST = "/api/web/getPushList";
    public static final String FIXED_PUSH = "/api/web/getFixedPush";
    public static final String DEL_PUSH = "/api/web/delPush";
    public static final String PUSH_DETAIL = "/api/web/getPushDetailById";
    public static final String READ_PUSH = "/api/web/readPush";
    public static final String READ_NOTICE = "/api/user/readNotice";
    public static final String UPLOAD_MSG = "/api/user/addAppUserMsg";
    public static final String DOWNLOAD_MSG = "/api/user/getAppUserMsg";


    private static OkHttpUtil okHttpUtil = null;

    public static OkHttpUtil getInstance() {

        if (okHttpUtil == null) {
            //加同步安全
            synchronized (OkHttpUtil.class) {
                if (okHttpUtil == null) {
                    okHttpUtil = new OkHttpUtil();
                }
            }
        }
        return okHttpUtil;
    }

    private static Handler mHandler = null;

    public synchronized Handler getHandler() {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }

        return mHandler;
    }

    public void getAsync(String url, Callback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public void getSync(String url, Callback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
        new Thread(() -> {
            try {
                Response response = call.execute();
                Log.e(TAG, "run: " + response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @SuppressWarnings("deprecation")
    public void postString(String url, String requestBody, Callback callback) {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(callback);
    }

    public void postStream(String url, byte[] data, Callback callback) {
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/x-markdown; charset=utf-8");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.write(data);
            }
        };

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(callback);
    }

    @SuppressWarnings("deprecation")
    public void postFile(String url, File file, Callback callback) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addPart(Headers.of("Content-Disposition", "form-data; " +
                "name=\"file\";filename=\"" + Tools.getUniquePsuedoID() + ".jpg\""), RequestBody.create(MediaType.parse("image/png"), file)
        ).build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    public void postDBFile(String url, String file, Callback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        byte[] readFile = Tools.readFile(file);
        if (readFile == null) {
            //noinspection ConstantConditions
            callback.onFailure(okHttpClient.newCall(null), new IOException());
            return;
        }
        String name = file.substring(file.lastIndexOf("/") + 1);
        builder.addPart(Headers.of("Content-Disposition", "form-data; " +
                "name=\"file\";filename=\"" + name + ".db\""), RequestBody.create(readFile)).build();

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    public void postForm(String url, Map<String, String> form, Callback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : form.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();

        okHttpClient.newCall(request).enqueue(callback);
    }

    public void postForm(String url, Map<String, String> header, Map<String, String> form, Callback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : form.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        Headers.Builder headers = new Headers.Builder();
        for (Map.Entry<String, String> entry : header.entrySet()) {
            headers.add(entry.getKey(), entry.getValue());
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .headers(headers.build())
                .build();

        okHttpClient.newCall(request).enqueue(callback);
    }

    public void download(String url, String downloadPath, @NotNull SipSession.Listener listener) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            //获取下载的内容输入流
            ResponseBody body = response.body();
            if (body == null) {
                listener.onError(null, -1, "ResponseBody为空");
                return;
            }
            byte[] bytes = body.bytes();
            FileOutputStream outputStream = new FileOutputStream(downloadPath);
            outputStream.write(bytes, 0, bytes.length);
            outputStream.flush();
            outputStream.close();

            listener.onRinging(null, null, downloadPath);
        } catch (IOException e) {
            listener.onError(null, -1, "IOException");
            e.printStackTrace();
        }
    }
}
